﻿using System.Collections.Generic;
using System.Linq;
using CID.Domain.Operations;
using CID.Domain.Users;
using CID.Web.Models.Operations;
using CID.Web.Support;
using NailsFramework.IoC;
using NailsFramework.Persistence;

namespace CID.Web.Controllers
{
    [CIDAuthorize(UserRole.Manager, UserRole.EnvironmentManager)]
    public class EnvironmentController : AjaxEnabledBaseCRUDController<IEnvironment, Environment, EnvironmentViewModel>
    {
        #region helper members
        [Inject]
        public IBag<User> Users { private get; set; }
        private IEnumerable<User> EnabledUsers { get { return Users.Where(x => x.Enabled); } }

        [Inject]
        public IBag<ServerRole> ServerRoles { private get; set; }
        private IEnumerable<ServerRole> EnabledServerRoles { get { return ServerRoles.Where(x => x.Enabled); } }

        [Inject]
        public IBag<Server> Servers { private get; set; }
        private IEnumerable<Server> EnabledServers { get { return Servers.Where(x => x.Enabled); } }
        #endregion

        protected override Environment CreateModel(EnvironmentViewModel viewModel)
        {
            return new Environment(viewModel.Name, viewModel.Description, Users.GetById(viewModel.ResponsibleId.Value));
        }

        protected override void PrepareViewModelForView(EnvironmentViewModel viewModel)
        {
            base.PrepareViewModelForView(viewModel);

            if (viewModel.ResponsibleId.HasValue && string.IsNullOrEmpty(viewModel.Responsible))
                viewModel.Responsible = Users.GetById(viewModel.ResponsibleId.Value).Name;

            viewModel.SetAvailableUsers(EnabledUsers);
            viewModel.SetAvailableServers(EnabledServers);
            viewModel.SetAvailableServerRoles(EnabledServerRoles);
        }
    }
}